package com.lp.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Configuration
public class GlobalExceptionConfig implements ErrorWebExceptionHandler {


    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 全局异常处理
     * @param exchange 交换器(request, response)
     * @param ex 出现异常时的异常对象
     * @return
     */
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        Map<String, String> result = new HashMap<>();
        //1.获取响应对象
        ServerHttpResponse response = exchange.getResponse();

        //2. response 是否结束(一般不用，可以用来处理多个异常的场景)
        if(response.isCommitted()) {
            return Mono.error(ex);
        }

        //3.设置响应头类型(JSON)
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        //4.设置响应状态码
        if (ex instanceof IllegalTokenException) {
            //是我们自定义的异常
            response.setStatusCode(HttpStatus.FORBIDDEN);
        } else {
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        }

        //5.处理统一异常响应
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            result.put("msg", ex.getMessage());
            try {
                return bufferFactory.wrap(objectMapper.writeValueAsBytes(result));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }));
    }

}
